package com.mk.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mk.constant.MessageConstant;
import com.mk.context.BaseContext;
import com.mk.entity.Friend;
import com.mk.result.Result;
import com.mk.service.IFriendService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 好友相关业务
 */
@RestController
@RequestMapping("/user/friend")
@RequiredArgsConstructor
public class FriendController {

    private final IFriendService friendService;
    private final Long userId = BaseContext.getCurrentId();

    /**
     * 判断对方是否已关注
     * @param targetUserId
     * @return
     */
    @CrossOrigin
    @GetMapping("/judge")
    public Result<String> judge(Long targetUserId) {
        Friend friend = friendService.getOne(new LambdaQueryWrapper<Friend>()
                .select(Friend::getStatus)
                .eq(Friend::getUserId, userId)
                .eq(Friend::getTargetUserId, targetUserId));
        if (friend == null || friend.getStatus().equals(Friend.ALREADY_CONCERNED)) {
            return Result.success(MessageConstant.ALREADY_CONCERNED);
        }
        return Result.success(MessageConstant.UN_CONCERNED);
    }

    /**
     * 关注好友
     * @param targetUserId
     * @return
     */
    @CrossOrigin
    @PostMapping("/save")
    public Result save(Long targetUserId) {
        Friend friend = Friend.builder()
                .userId(userId)
                .targetUserId(targetUserId)
                .status(Friend.ALREADY_CONCERNED)
                .createTime(LocalDateTime.now())
                .build();
        friendService.save(friend);
        return Result.success();
    }

    /**
     * 取消关注好友
     * @param targetUserId
     * @return
     */
    @CrossOrigin
    @DeleteMapping("/cancel")
    public Result cancel(Long targetUserId) {
        Friend friend = Friend.builder()
                .userId(userId)
                .targetUserId(targetUserId)
                .build();
        friendService.removeById(friend);
        return Result.success();
    }

}
